﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HiSport.Application.HiSportService.Bas.BasVenueMemberManagement.Dtos;
using HiSport.Core.Entity;
using HiSport.Core.Entity.HiSportEntity.Bas;
using HiSport.Core.Util;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HiSport.Application.HiSportService.Bas.BasVenueMemberManagement.Service
{

    //[ApiDescriptionSettings("会员管理", Tag = "会员信息", SplitCamelCase = false)]
    [ApiDescriptionSettings("MemberManagement", Tag = "MemberInformation", SplitCamelCase = false)]
    public class BasVenueMemberService : ITransient, IDynamicApiController, IBasVenueMemberService
    {
        /// <summary>
        /// 会员
        /// </summary>
        private readonly SqlSugarRepository<BasVenueMember> _venueMember;

        /// <summary>
        /// 系统会员会员
        /// </summary>
        private readonly SqlSugarRepository<SysMember> _sysMember;


        public BasVenueMemberService(SqlSugarRepository<BasVenueMember> venueMember,
            SqlSugarRepository<SysMember> sysMember)
        {
            _venueMember = venueMember;
            _sysMember = sysMember;

        }


        /// <summary>
        /// 查询 场馆(租户)会员
        /// </summary>
        /// <param name="indexDto"></param>
        /// <returns></returns>
        public async Task<SqlSugarPagedList<VenueMemberDto>> Page(VenueMemberPageIndexDto inputDto)
        {
            return await _venueMember.AsQueryable()
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Name), u => u.Name.Contains(inputDto.Name.Trim()))
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Phone), u => u.Phone.Contains(inputDto.Phone.Trim()))
                .WhereIF(inputDto.IsFans.HasValue, u => u.IsFans==inputDto.IsFans)
                .OrderBy(u => u.CreateTime, OrderByType.Desc)
                .Select(u => new VenueMemberDto()
                {
                    Id = u.Id.SelectAll(),
                })
                .ToPagedListAsync(inputDto.Page, inputDto.PageSize);
        }


        /// <summary>
        /// 新增场馆（租户）会员或粉丝
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>       
        [ApiDescriptionSettings(Name = "Create"), HttpPost]
        [DisplayName("新增场馆（租户）会员或粉丝")]
        [UnitOfWork]
        public async Task<bool> Create(VenueMemberCreateOrUpdateDto inputDto)
        {
            if (string.IsNullOrEmpty(inputDto.Name))
            {
                inputDto.Name = inputDto.Phone;
            }

            //添加平台会员
            var res = true;
            var sysData = await _sysMember.GetFirstAsync(x => x.Phone == inputDto.Phone);
            if (sysData == null)
            {
                res = await _sysMember.InsertAsync(new SysMember()
                {
                    Birthday = inputDto.Birthday,
                    HeadUrl = inputDto.HeadUrl,
                    CreateTime = DateTime.Now,
                    Name = inputDto.Name,
                    Phone = inputDto.Phone,
                    Sex = inputDto.Sex,
                    OpenId = "",
                });
                if (!res)
                {
                    throw Oops.Oh("系统会员添加失败");
                }
            }

            //添加场馆(租户)会员
            var basData = await _venueMember.GetFirstAsync(x => x.Phone == inputDto.Phone);
            if (basData == null)
            {
                res = await _venueMember.InsertAsync(new BasVenueMember()
                {
                    Birthday = inputDto.Birthday,
                    HeadUrl = inputDto.HeadUrl,
                    CreateTime = DateTime.Now,
                    Name = inputDto.Name,
                    Phone = inputDto.Phone,
                    Sex = inputDto.Sex,
                    IsFans=inputDto.IsFans,
                    SignupSource=inputDto.SignupSource,
                });
                if (!res)
                {
                    throw Oops.Oh("会员添加失败");
                }
            }
            else
            {
                throw Oops.Oh("会员已存在");
            }

            return res;
        }

        /// <summary>
        /// 修改场馆（租户）会员或粉丝
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>       
        [ApiDescriptionSettings(Name = "Update"), HttpPost]
        [DisplayName("修改场馆（租户）会员或粉丝")]
        public async Task<bool> Update(VenueMemberCreateOrUpdateDto inputDto)
        {
            var res = true;
            var basData = await _venueMember.GetFirstAsync(x => x.Phone == inputDto.Phone);
            if (basData != null)
            {
                basData.Birthday = inputDto.Birthday;
                basData.HeadUrl = inputDto.HeadUrl;
                basData.Name = inputDto.Name;
                basData.Sex = inputDto.Sex;
                basData.Birthday=inputDto.Birthday;
                res = await _venueMember.UpdateAsync(basData);
                if (!res)
                {
                    throw Oops.Oh("会员修改失败");
                }
            }

            if (basData == null && basData == null)
            {
                throw Oops.Oh("会员不存在");
            }

            return res;
        }

        /// <summary>
        /// 修改场馆（租户）会员或粉丝
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>       
        [ApiDescriptionSettings(Name = "UpdateVenueMemberGrade"), HttpPost]
        [DisplayName("修改场馆（租户）会员或粉丝")]
        public async Task<bool> UpdateVenueMemberGrade(VenueMemberGradeUpdateDto inputDto)
        {
            var res = true;
            var basData = await _venueMember.GetFirstAsync(x => x.Phone == inputDto.Phone);
            if (basData != null)
            {
                basData.MemberGradeId = inputDto.MemberGradeid;
                if (basData.IsFans)
                {
                    throw Oops.Oh("粉丝不能修改等级");
                }
                res = await _venueMember.UpdateAsync(basData);
                if (!res)
                {
                    throw Oops.Oh("会员等级修改失败");
                }
            }
            else
            {
                throw Oops.Oh("会员不存在");
            }

            return res;
        }

        /// <summary>
        /// 会员转粉丝
        /// </summary>
        /// <returns></returns>
        [ApiDescriptionSettings(Name = "FansConvertMember"), HttpPost]
        public async Task<bool> FansConvertMember(string phone)
        {
            var res = true;
            var basData = await _venueMember.GetFirstAsync(x => x.Phone == phone);
            if (basData != null)
            {
                basData.IsFans = false;
                res = await _venueMember.UpdateAsync(basData);
                if (!res)
                {
                    throw Oops.Oh("转换失败");
                }
            }

            if (basData == null && basData == null)
            {
                throw Oops.Oh("粉丝信息不存在");
            }

            return res;
        }


    }
}
